package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.server.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

    @Service
    public class TodayBestService {

        @DubboReference(version = "1.0.0")
        private RecommendUserApi recommendUserApi;

        //TODO 可以进一步的优化，将默认配置写入到nacos中
        @Value("${tanhua.sso.default.user}")
        private Long defaultUser;

        @Autowired
        private UserService userService;

        @DubboReference(version = "1.0.0")
        private UserInfoApi userInfoApi;

        public TodayBest queryTodayBest(String token) {
            //校验token是否有效
            Long userId = this.userService.checkToken(token);
            if (null == userId) {
                //提示用户登录
                return null;
            }

            //通过远程的服务查询今日佳人
            RecommendUser recommendUser = this.recommendUserApi.queryWithMaxScore(userId);
            if (recommendUser == null) {
                //给出一个默认的推荐用户
                recommendUser = new RecommendUser();
                recommendUser.setUserId(defaultUser);
                recommendUser.setToUserId(userId);
                //随机计算得分
                recommendUser.setScore(RandomUtil.randomDouble(80, 99));
            }

            TodayBest todayBest = new TodayBest();
            todayBest.setFateValue(recommendUser.getScore().longValue()); //缘分值

            //查询用户信息
            UserInfo userInfo = this.userInfoApi.queryByUserId(recommendUser.getUserId());
            BeanUtil.copyProperties(userInfo, todayBest, "id");
            todayBest.setId(userInfo.getUserId());
            // 性别，将枚举的name转成小写
            todayBest.setGender(userInfo.getSex().name().toLowerCase());

            return todayBest;
        }
}
